package view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

public class ProgressDialog extends Dialog
{
	private Shell parent;
	private String message;
	private Shell dialog;

	public ProgressDialog(Shell parent, String message)
	{
		super(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
		this.parent = parent;
		this.message = message;
	}

	public void open()
	{
		final Display display = parent.getDisplay();
		dialog = new Shell(parent, getStyle());
		dialog.setLayout(new GridLayout(2, false));
		Rectangle parentBounds = parent.getBounds();
		int width = 300;
		int height = 200;
		dialog.setBounds(parentBounds.x + width/2 , parentBounds.y + height/2, width, height);
		Font font = (Font) parent.getData("font");

		Label messageLabel = new Label(dialog, SWT.NONE);
		messageLabel.setFont(font);
		messageLabel.setText(message);
		ProgressBar progressBar = new ProgressBar(dialog, SWT.HORIZONTAL);
		progressBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		progressBar.setMinimum(0);
		progressBar.setMaximum(100);
		GridData gridData = new GridData();
		gridData.horizontalSpan = 2;
		progressBar.setLayoutData(gridData);

		CLabel timeLabel = new CLabel(dialog, SWT.NONE);
		timeLabel.setFont(font);
		timeLabel.setText("Time elapsed: ");

		final CLabel timeUpdate = new CLabel(dialog, SWT.NONE);
		timeUpdate.setFont(font);
		timeUpdate.setText("0.000 Seconds elapsed ");
		timeUpdate.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		final long startTime = System.currentTimeMillis();

		final Runnable timeUpdateRunner = new Runnable() 
		{
			@Override
			public void run()
			{
				int time = (int) (System.currentTimeMillis() - startTime);
				int seconds = time / 1000;
//				System.out.println(seconds);
				int millis = time - (seconds * 1000);
				timeUpdate.setText(seconds + "." + millis + " Seconds elapsed");
				display.timerExec(1, this);
			}};
		display.timerExec(1, timeUpdateRunner);

		dialog.addDisposeListener(new DisposeListener(){
			@Override
			public void widgetDisposed(DisposeEvent e) {
				display.timerExec(-1, timeUpdateRunner);
			}});
		dialog.pack();
		dialog.setData("progress", progressBar);
		dialog.setData("dialog", dialog);
		dialog.open();
	}

	public boolean isDisposed()
	{
		return dialog.isDisposed();
	}

	public Object getData(String key)
	{
		return dialog.getData(key);
	}
}
